using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Agatha.Common;
using Agatha.Common.InversionOfControl;
using Source.Common;


namespace  Source.Web.FrameWork
{

    public class UserControl<T> : System.Web.UI.UserControl, IViewPart
        where T : IPartController
    {
        private MessageHelper messageHelper;
        protected T Controller { get; private set; }

        protected UserControl()
        {
            Disposer.RegisterForGuaranteedDisposal(this);
            Controller = ((ICastleContainer)IoC.Container).Resolve<T>(new { ViewPart = this });
        }

        public override void Dispose()
        {
            IoC.Container.Release(Controller);
            Controller.Dispose();
            base.Dispose();
        }

        protected override void OnInit(System.EventArgs e)
        {
            base.OnInit(e);
            messageHelper = new MessageHelper((BasePage)Page, new TextRepositoryManager());
        }

        public IPartController GetUntypedPartController(IRequestDispatcher dispatcher)
        {
            return GetPartController(dispatcher);
        }

        public T GetPartController(IRequestDispatcher dispatcher)
        {
            Controller.SetDispatcher(dispatcher);
            return Controller;
        }

        public IDictionary State
        {
            get { return ViewState; }
        }

        public void DisplayMessages(string message)
        {
            DisplayMessages(new[] { message }, null);
        }

        public void DisplayMessages(string message, params string[] parameters)
        {
            DisplayMessages(new[] { message }, new[] { parameters.ToList() });
        }

        public void DisplayMessages(IEnumerable<string> messages)
        {
            DisplayMessages(messages, null);
        }

        public void DisplayMessages(IEnumerable<string> messages, IEnumerable<IEnumerable<string>> parameters)
        {
            messageHelper.DisplayMessages(messages, parameters);
        }

        public void DisplayMessageBox(string message)
        {
            messageHelper.DisplayMessageBox(message);
        }
    }
}